/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.mochaccino.framework.dbtool.impl;

import ch.qos.logback.core.joran.spi.JoranException;
import com.google.code.mochaccino.framework.dbtool.CommandLine;
import com.google.code.mochaccino.framework.dbtool.liquibase.LiquibaseProviderHibernate;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class Create extends CommandLine {
	private Option  OPT_CREATE_SCHEMA = null;
	private boolean createSchema      = true;

	/** Constructor */
	public Create() throws JoranException {
		super();
	}

	@Override
	protected Options createOptions() {
		Options options = new Options();
		options.addOption( OPT_MODULE );

		OPT_CREATE_SCHEMA = new Option( "create", false, "Create schema automatically for you." );
		OPT_CREATE_SCHEMA.setRequired( false );
		options.addOption( OPT_CREATE_SCHEMA );
		return options;
	}

	@Override
	protected void interpretArgsBeforeInjection( String[] args ) {
		super.interpretArgsBeforeInjection( args );

		try {
			org.apache.commons.cli.CommandLine parsedArgs = parseArgs( args );
			createSchema = parsedArgs.hasOption( OPT_CREATE_SCHEMA.getOpt() );
		} catch ( ParseException e ) {
			exit( 2, e );
		}
	}

	@Override
	protected void execute() {
		LiquibaseProviderHibernate provider = new LiquibaseProviderHibernate( target, configuration );
		try {
			provider.initialize();
			if ( createSchema ) {
				provider.createSchema();
			}
		} catch ( Exception e ) {
			exit( 2, e );
		} finally {
			try {
				provider.destroy();
			} catch ( Exception e ) {
				exit( 2, e );
			}
		}
	}

	public static final void main( String[] args ) throws JoranException {
		Create tool = new Create();
		tool.start( args );
	}
}
